Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
int longestPalindrome(char * s){
}
本題是Greedy的第二題,這個主題似乎都喜歡叫你找最大值,給一個由小寫或大寫字母所組成的字串,回傳由這些字母可以形成的最長迴文 (Palindrome)有多長?所謂的迴文就是由右讀到左和由左讀到右是完全相同的。
int longestPalindrome(char * s){
int char_array[128] = {0};
int i;
int only_one_char_flag = 0, odd_number_char_flag = 0, ret = 0;
i = 0;
while (s[i] != '\0') {
char_array[s[i]] += 1;
i++;
}
for (i=0; i<128; i++) {
if (char_array[i] == 0) {
continue;
}
if ((odd_number_char_flag == 0) && ((char_array[i] % 2) == 1)) { // 判斷是不是第一次出現奇數次
ret += char_array[i];
odd_number_char_flag = 1;
} else if ((char_array[i] % 2) == 1) { // 判斷是奇數次
ret += char_array[i] - 1;
} else if ((char_array[i] % 2) == 0) { // 判斷是偶數次
ret += char_array[i];
}
}
return ret;
}